package com.guomei.interceptor;

import com.guomei.configs.JwtConfig;
import com.guomei.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtConfig jwtConfig;

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 获取请求路径
            String requestURI = request.getRequestURI();
            String method = request.getMethod();
            log.info("拦截到请求 - URI: {}, 方法: {}, 原始URI: {}", requestURI, method, request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI));
            // 检查是否为排除路径
            if (isExcludePath(requestURI)) {
                return true;
            }

            // 从header中获取token
            String authHeader = request.getHeader(jwtConfig.getHeader());

            // 检查token是否存在
            if (authHeader == null || !authHeader.startsWith(jwtConfig.getTokenPrefix())) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"未提供有效的认证令牌\"}");
                return false;
            }

            // 提取token
            String token = authHeader.substring(jwtConfig.getTokenPrefix().length());

            // 验证token
            if (!JwtUtil.validateToken(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"令牌无效或已过期\"}");
                return false;
            }

            // 检查是否为refreshToken
            if (JwtUtil.isRefreshToken(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"不能使用刷新令牌访问接口\"}");
                return false;
            }

            // 将用户信息存储到request中供后续使用
            request.setAttribute("userId", JwtUtil.getUserIdFromToken(token));
            request.setAttribute("username", JwtUtil.getUsernameFromToken(token));

            return true;
        } catch (Exception e) {
            // 记录日志但不中断请求，让其他异常处理器处理
            log.error("JWT拦截器处理异常: {}", e.getMessage(), e);
            // 不应该在这里直接返回错误，应该让请求继续，由其他处理器处理
            throw e; // 重新抛出异常，让全局异常处理器处理
        }
    }

    /**
     * 判断是否为排除路径
     */
    private boolean isExcludePath(String requestURI) {
        return Arrays.stream(jwtConfig.getExcludePaths())
                .anyMatch(pattern -> pathMatcher.match(pattern, requestURI));
    }
}
